package org.tigris.atlas.persist.hibernate;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;

import org.apache.commons.lang.enums.Enum;
import org.apache.commons.lang.enums.EnumUtils;

public class NamedEnumerationUserType extends AbstractEnumerationUserType {
	
	private static final int[] SQL_TYPES = new int[] {Types.VARCHAR};
	
	public NamedEnumerationUserType(Class enumerationClass) {
		super(enumerationClass);
	}

	/**
	 * @see org.hibernate.usertype.UserType#sqlTypes()
	 */
	public int[] sqlTypes() {
		return SQL_TYPES;
	}

	protected void setValue(PreparedStatement ps, Object value, int index) throws SQLException {
		Enum enumInstance = (Enum) value;
        
		if (enumInstance != null) {
	        //convert the enum into its persistence format		
	        String enumCode = enumInstance.getName();
	        
	        //set the value into the resultset
	        ps.setString(index, enumCode);
	        
		} else {
			ps.setNull(index, Types.VARCHAR);
			
		}
	}
	
	protected Enum getEnum(String enumerationCode) {
		return EnumUtils.getEnum(getEnumerationClass(), enumerationCode);
	}	

}
